<template>
  <div>
    <!-- 搜索表单 -->
    <el-form :inline="true" :model="formData" class="demo-form-inline">
      <el-form-item label="分类名称">
        <el-input v-model="formData.typeName" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>
    <el-form style=" float: right; margin-right: 20px;margin-bottom: 20px">
      <el-button type="primary" round @click="add">添加</el-button>
    </el-form>
    <el-table
      :data="tableData"
      style="width: 100%"
      row-key="id"
      border
      lazy
      :load="load"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column
        prop="type_name"
        label="分类名称"
        header-align="center"
        align="center"
      />
      <el-table-column
        prop="createTime"
        label="创建时间"
        header-align="center"
        align="center"
      />
      <el-table-column label="操作" header-align="center" align="center">
        <template v-slot="{ row }">
          <el-button
            v-if="row.hasChildren"
            type="primary"
            size="small"
            @click="save(row.code)"
            >添加</el-button
          >
          <el-button
            type="primary"
            size="small"
            @click="update(row.type_name, row.table_type, row.code)"
            >编辑</el-button
          >
          <el-button type="danger" size="small" @click="del(row.code)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 新增一级分类弹窗 -------------------->
    <el-dialog v-model="dialogVisible" title="添加分类" width="30%" draggable>
      <el-form ref="addFormRef" :model="addForm" :rules="rules">
        <el-form-item label="分类名称" prop="type_name">
          <el-input v-model="addForm.typeName" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="表格类型" prop="table_type">
          <el-select v-model="addForm.tableType" placeholder="请选择表格类型">
            <el-option label="斑马型" value="斑马型" />
            <el-option label="五彩斑斓型" value="五彩斑斓型" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAdd">确认</el-button>
      </template>
    </el-dialog>
    <!--结束----------------------------------------->
    <!-- 新增二级分类弹窗 -------------------->
    <el-dialog
      v-model="subDialogVisible"
      title="添加子分类"
      width="30%"
      draggable
    >
      <el-form ref="subAddFormRef" :model="subAddForm" :rules="subRules">
        <el-form-item label="分类名称" prop="type_name">
          <el-input
            v-model="subAddForm.typeName"
            placeholder="请输入子分类名称"
          />
        </el-form-item>
        <el-form-item label="表格类型" prop="table_type">
          <el-select
            v-model="subAddForm.tableType"
            placeholder="请选择表格类型"
          >
            <el-option label="斑马型" value="斑马型" />
            <el-option label="五彩斑斓型" value="五彩斑斓型" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="subDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubAdd">确认</el-button>
      </template>
    </el-dialog>
    <!------------------------------------------------>
    <!--修改分类弹窗------------------------------------------>
    <el-dialog v-model="visiable" title="修改子分类" width="30%" draggable>
      <el-form ref="updateFormRef" :model="updateForm" :rules="updateRules">
        <el-form-item label="分类名称" prop="type_name">
          <el-input
            v-model="updateForm.typeName"
            placeholder="请输入子分类名称"
          />
        </el-form-item>
        <el-form-item label="表格类型" prop="table_type">
          <el-select
            v-model="updateForm.tableType"
            placeholder="请选择表格类型"
          >
            <el-option label="斑马型" value="斑马型" />
            <el-option label="五彩斑斓型" value="五彩斑斓型" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="visiable = false">取消</el-button>
        <el-button type="primary" @click="handleUpdate">确认</el-button>
      </template>
    </el-dialog>
    <!-------------------------------------->
    <div
      style="
        display: flex;
        justify-content: center;
        height: 50px;
        margin-top: 20px;
        line-height: 50px;
        text-align: right;
      "
    >
      <el-pagination
        background
        :page-size="pageSize"
        :page-sizes="[2, 5, 10, 20, 50]"
        layout="total,sizes,prev, pager, next,jumper"
        :total="total"
        @size-change="chgsize"
        @current-change="chgpg"
      />
    </div>
  </div>
</template>
<script lang="ts" setup>
import { ref } from "vue";
import {
  queryCategory,
  saveCategory,
  updateCategory,
  deleteCategory
} from "@/api/product/product.js";
import { onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage, ElMessageBox, ElTable } from "element-plus";

const router = useRouter();

interface User {
  code: number;
  type_name: string;
  createTime: string;
  pid?: number;
  hasChildren?: boolean;
  children?: User[];
}

const load = async (
  row: User,
  treeNode: unknown,
  resolve: (data: User[]) => void
) => {
  try {
    const res = await queryCategory({
      pid: row.code // 传递当前节点的code作为父级ID
    });
    resolve(
      res.data.data.map(item => ({
        ...item,
        hasChildren: item.hasChildren ?? false
      }))
    );
  } catch (error) {
    console.error("加载子节点失败:", error);
    resolve([]);
  }
};
// 新增一级分类弹窗相关代码---------------------------
const dialogVisible = ref(false);
const addFormRef = ref(null);
const addForm = ref({
  typeName: "",
  tableType: "",
  pid: 1 // 默认父级ID为1
});
const rules = {
  typeName: [{ required: true, message: "分类名称不能为空", trigger: "blur" }]
};

async function handleAdd() {
  try {
    await addFormRef.value.validate();
    const res = await saveCategory(addForm.value);
    if (res.code === 200) {
      ElMessage.success("添加成功");
      dialogVisible.value = false;
      initData();
      router
        .replace("/refresh")
        .then(() => router.replace("/product/category"));
    }
  } catch (error) {
    console.log("添加失败:", error);
  }
}

// 修改现有的add方法
function add() {
  addForm.value = { typeName: "", tableType: "", pid: 1 }; // 重置表单
  dialogVisible.value = true;
}
//-------------------------------------------------
//新增二级分类--------------------------------
const subDialogVisible = ref(false);
const subAddFormRef = ref(null);
const subAddForm = ref({
  typeName: "",
  tableType: "",
  pid: 0
});
const subRules = {
  typeName: [{ required: true, message: "子分类名称不能为空", trigger: "blur" }]
};

function save(pid) {
  subAddForm.value = { typeName: "", tableType: "", pid };
  subDialogVisible.value = true;
}

async function handleSubAdd() {
  try {
    await subAddFormRef.value.validate();
    const res = await saveCategory(subAddForm.value);
    if (res.code === 200) {
      ElMessage.success("子分类添加成功");
      subDialogVisible.value = false;
      initData();
      router
        .replace("/refresh")
        .then(() => router.replace("/product/category"));
    }
  } catch (error) {
    console.log("子分类添加失败:", error);
  }
}
//--------------------------------------------
//修改分类弹窗--------------------------------
const visiable = ref(false);
const updateFormRef = ref(null);
const updateForm = ref({
  typeName: "",
  tableType: "",
  code: 0
});
const updateRules = {
  typeName: [{ required: true, message: "子分类名称不能为空", trigger: "blur" }]
};

function update(name, type, code) {
  updateForm.value = { typeName: name, tableType: type, code: code };
  visiable.value = true;
}
async function handleUpdate() {
  try {
    await updateFormRef.value.validate();
    const res = await updateCategory(updateForm.value);
    if (res.code === 200) {
      ElMessage.success("子分类修改成功");
      visiable.value = false;
      initData();
      router
        .replace("/refresh")
        .then(() => router.replace("/product/category"));
    }
  } catch (error) {
    console.log("子分类修改失败:", error);
  }
}
//-------------------------------------------

function del(id) {
  ElMessageBox.confirm("你确定要删除吗?", "Warning", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      deleteCategoryByCode(id);
    })
    .catch(() => {});
  // 这里添加实际的删除逻辑
}

async function deleteCategoryByCode(id) {
  let res = await deleteCategory(id);
  if (res.code == 200) {
    ElMessage({
      message: "删除成功",
      type: "success"
    });
    initData();
    router.replace("/refresh").then(() => router.replace("/product/category"));
  }
}

const tableData = ref([]);

const page = ref(1); //当前页 默认第1页
const pageSize = ref(5); //每页记录数
const total = ref(0); //总记录数

//每页记录数变化
function chgsize(size) {
  //更改每页记录数
  pageSize.value = size;
  //从每页开始查询
  page.value = 1;
  //查询数据
  initData();
}

function chgpg(pg) {
  //更改当前页
  page.value = pg;
  //查询数据
  initData();
}

// 表单数据
const formData = ref({
  typeName: ""
});

async function initData() {
  let data = {
    page: page.value,
    pageSize: pageSize.value,
    typeName: formData.value.typeName,
    pid: 1
  };
  let res = await queryCategory(data);
  console.log(res);
  if (res.code == 200) {
    tableData.value = res.data.data.map(item => ({
      ...item,
      hasChildren: item.hasChildren ?? true
    }));
    total.value = res.data.total;
    page.value = res.data.page;
    pageSize.value = res.data.pageSize;
  }
}

// 查询操作
const handleQuery = () => {
  // 这里添加实际的查询逻辑
  initData();
};

// 重置表单
const handleReset = () => {
  formData.value.typeName = "";
  initData();
};
onMounted(() => {
  initData();
});
</script>
